/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.pekall.myDictionary.utils;

import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.net.NetworkInfo.State;
import android.text.TextUtils;
import android.util.Log;

public class Utils {
    private static final String TAG = Utils.class.getSimpleName();

    private static final int BUFFER_SIZE = 8192;

    private static final String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)";

    private static final int CONN_TIME_OUT = 20 * 1000;

    private static final int READ_TIME_OUT = 20 * 1000;

    /**
     * Prevent from creating instance of this class
     */
    private Utils() {
    }

    /**
     * Test if network is connected.
     * 
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        NetworkInfo networkInfo = getActiveNetworkInfo(context);
        return networkInfo != null && networkInfo.isConnected();
    }

    private static NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return null;
        }
        return connectivity.getActiveNetworkInfo();
    }

    public static boolean isWifiConnected(Context context) {
        return getNetworkState(context, ConnectivityManager.TYPE_WIFI) == State.CONNECTED;
    }

    public static boolean isMobileConnected(Context context) {
        return getNetworkState(context, ConnectivityManager.TYPE_MOBILE) == State.CONNECTED;
    }

    private static State getNetworkState(Context context, int networkType) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(networkType);

        return info == null ? null : info.getState();
    }

    public static HttpClient createHttpClient(Context context) {

        // 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）
        HttpParams httpParams = new BasicHttpParams();

        // 设置连接超时和 Socket 超时，以及 Socket 缓存大小
        HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
        HttpConnectionParams.setSocketBufferSize(httpParams, BUFFER_SIZE);

        // 设置重定向，缺省为 true
        HttpClientParams.setRedirecting(httpParams, true);

        // 检测代理设置
        String proxyHost = Proxy.getHost(context);
        int proxyPort = Proxy.getPort(context);

        Log.d(TAG, "[createHttpClient] proxyHost = " + proxyHost);
        Log.d(TAG, "[createHttpClient] proxyPort = " + proxyPort);

        boolean isWifiConnected = Utils.isWifiConnected(context);
        boolean isMobileConnected = Utils.isMobileConnected(context);

        Log.d(TAG, "[createHttpClient] isWifiConnected = " + isWifiConnected);
        Log.d(TAG, "[createHttpClient] isMobileConnected = " + isMobileConnected);

        if (!isWifiConnected && !TextUtils.isEmpty(proxyHost)) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            Log.d(TAG, "Set proxy: host: " + proxyHost + " port:" + proxyPort);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // 设置 user agent
        String userAgent = USER_AGENT;
        HttpProtocolParams.setUserAgent(httpParams, userAgent);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

}
